﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using Core.Validation;
using Domain;

namespace DAValidationWeb
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var node = new Node
                               {
                                   Name = txtName.Text
                               };

                SaveNode(node);


            }
            catch (RulesException ex)
            {
                foreach (var validationError in ex._errors)
                {
                    Page.Validators.Add(validationError);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        private void SaveNode(Node node)
        {

            var err = DataAnnotationsValidationRunner.GetErrors(node);
            if (err.Count() > 0)
            {
                throw new RulesException(err.ToList());
            }

            //Other Business Validation
            var exc = new List<ValidationError>();
            exc.Add(new ValidationError("Name", "My Business Validation error."));
            throw new RulesException(exc);

            //TODO save to database now

        }
    }
}
